<template>
  <div class="flex items-center justify-center h-screen">
    <div class="flex flex-col items-center">
      <img class="w-20 h-20" src="/public/logo.png" alt="logo">
      <h1 class="text-3xl mb-4"></h1>
      <el-form ref="ruleFormRef" :model="form" :rules="rules" label-position="right">
        <el-form-item prop="username" label="用户名:" label-width="80px">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码:" label-width="80px">
          <el-input type="password" v-model="form.password" placeholder="请输入密码" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="checkPass" label="确认密码:" label-width="80px">
          <el-input type="password" v-model="form.checkPass" placeholder="请再次输入密码" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="w-full" type="primary" @click="registerFun">注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import router from "../../router";
import {register} from '@/api/user.js'
import {reactive, ref} from 'vue'
import {ElMessage} from "element-plus";

const ruleFormRef = ref(null)
const validatePass = (rule, value, callback) => {
  if (value !== form.value.password) {
    callback(new Error('两次输入的密码不一致'))
    return
  }
  callback()
}
const form = ref({
  username: '',
  password: '',
  checkPass: ''
})

const rules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 5, max: 10, message: '长度在6到10个字符', trigger: 'blur'}
  ],
  password: [{required: true, message: '请输入密码', trigger: 'blur'}],
  checkPass: [{validator: validatePass, trigger: 'blur'}]
}

const registerFun = async () => {
  ruleFormRef.value.validate(async valid => {
    if (valid) {
      const res = await register(form.value)
      ElMessage({
        type: 'success',
        message: res.msg
      })
      setTimeout(()=>{
         router.push('login')
      }, 2000)
    } else {
      console.log('error submit')
      return false
    }
  })
}

const toRegister = () => {
  router.push('login')
}

</script>

<style scoped>

</style>
